package main

import (
	"fmt"
	"sync"
)

// 可以收集书籍数据 方便别人使用
func main() {
	var wait = sync.WaitGroup{}
	wait.Add(3)
	go func() {
		doJob("isbn_test_file.txt", "out1.xlsx", 1)
		wait.Done()
		fmt.Printf("第一任务完成")
	}()
	go func() {
		doJob("isbn_test_file.txt", "out2.xlsx", 2)
		wait.Done()
		fmt.Printf("第二任务完成")
	}()
	go func() {
		doJob("isbn_test_file.txt", "out3.xlsx", 3)
		wait.Done()
		fmt.Printf("第三任务完成")
	}()
	wait.Wait()
}

func doJob(read, write string, version int) {
	// 读取文件
	books, err := ReadIsbnFromFile(read)
	if err != nil {
		fmt.Println(err)
		return
	}
	// 调用接口
	var resultBooks []*BookItem
	for i := range books {
		//time.Sleep(time.Second)
		var isbn []*BookItem
		var err error
		switch version {
		case 1:
			isbn, err = QueryIsbn(books[i].Isbn)
		case 2:
			isbn, err = QueryIsbn2(books[i].Isbn)
		case 3:
			isbn, err = QueryIsbn3(books[i].Isbn)
		}

		if err != nil {
			fmt.Printf("isbn:%v 取信息错误:%v\n", books[i].Isbn, err)
			resultBooks = append(resultBooks, books[i])
			continue
		}
		if len(isbn) == 0 {
			resultBooks = append(resultBooks, books[i])
		} else {
			for i2 := range isbn {
				isbn[i2].Index = books[i].Index
			}
			resultBooks = append(resultBooks, isbn...)
		}
		fmt.Println(len(isbn), ToJson(isbn))
	}
	// 保存到文件中
	err = SaveToExcel(write, resultBooks)
	if err != nil {
		fmt.Println(err)
		return
	}
}
